<?php
namespace Common\Model;

use Think\Model;

class ProblemModel extends  CommonModel {

	public $tableName = 'problem';
	//状态
	public $status = [
		1 => '启用',
		2 => '禁用',
	];
	//type
	public $types = [
		1 => '文本',
		2 => '单选',
		3 => '多选'
	];


	//查询渠道列表
	public function get_problem_list(array $params,$field="a.*"){
		$where = [];
		$pagesize = empty($params['pageSize']) ? '20' : $params['pageSize'];
		$params["problem_name"]?$where['a.problem_name'] = ["LIKE","%{$params['problem_name']}%"]:"";
		$params['status']?$where['a.status'] = $params['status']:"";
		$params['type']?$where['a.type'] = $params['type']:"";

		$count = $this
			->alias("a")
			->where($where)
			->count();
		$Page = new \Think\Page($count, $pagesize);
		$limit = $Page->firstRow . ',' . $Page->listRows;

		$list = $this
			->alias("a")
			->field($field)
			->where($where)
			->order("a.id desc")
			->limit($limit)
			->order($params['order']?$params['order']:"a.id desc")
			->select();
		int_to_string($list,['status'=>$this->status]);
		int_to_string($list,['type'=>$this->types]);
		$data = [
			'count' => $count,
			'list'  => $list
		];
		return $data;
	}




	//添加/修改渠道
	public function problem_save(array $params){
		$where = [
			'problem_name' => $params['problem_name'],
		];
		$condition = [
			'sort' => $params['sort']
		];
		if($params['problem_id']){
			$where['id'] = ['neq',$params['problem_id']];
			$condition['id'] = ['neq',$params['problem_id']];
		}

		$info = $this->where($where)->find();
		if($info) return $this->returnData("问题名称已存在,请重新输入");


		$problem_info = $this->where($condition)->find();
		if($problem_info) return $this->returnData('排序已存在,请重新输入');


		foreach($params['answer_options'] as $key=>$val){
			if(empty($val['answer'])) unset($params['answer_options'][$key]);
		}
		$params['answer_options'] =  array_values($params['answer_options']);
		if($params['type'] != 1 && empty($params['answer_options']))  return $this->returnData('答案选项不能为空');
		$data = [
			'problem_name'   => $params['problem_name'],
			'type'  		 => $params['type'],
			'status'         => $params['status'],
			'answer_options' => json_encode($params['answer_options']?$params['answer_options']:[]),
//			'is_calculated'  => $params['is_calculated']?$params['is_calculated']:2,
			'is_menu'		 => $params['is_menu'],
			'sort'			 => $params['sort']
		];
		if($params['problem_id']){
			$data['update_time'] = time();
			$data['update_by'] = $params['userId'];
			$result = $this->where(['id'=>$params['problem_id']])->save($data);
		}else{
			$data['create_time'] = time();
			$data['create_by'] = $params['userId'];
			$result = $this->add($data);
		}
		return $this->returnData($result?"设置成功":"设置失败",$result?200:500);
	}
}

?>
